<template>
	<view class="u-page">
		<!-- 顶部状态栏占位 -->
		<view class="status-bar-placeholder"></view>
		<!-- Logo区域 -->
		<view>
			<!-- <up-image 
				src="/static/logo.png" 
				width="80px" 
				height="80px" 
				mode="aspectFit">
			</up-image> -->
			<up-text color="#fff" text="注册账号" size="24px" bold
				custom-style="margin: 30px 40px 60px; text-align: left; display: block; width: 100%;">
			</up-text>
		</view>

		<!-- 注册表单区域 -->
		<view class="login-form">
			<up-form class="edit-form" :model="loginForm" ref="form" :rules="rules">
				<!-- 手机号输入框 -->
				<up-form-item label="手机号" prop="phone" labelWidth="70"
					>
					<up-input v-model="loginForm.phone" placeholder="请输入手机号" border="none"
						placeholder-style="color: #888888"></up-input>
				</up-form-item>

				<!-- 验证码输入框 -->
				<up-form-item label="验证码" prop="code" border="none" labelWidth="70"  style="padding: 0px 10px;"
					>
					<up-input v-model="loginForm.code" border="none" placeholder="请填写验证码"
						placeholder-style="color: #888888" >
						<template #suffix>
							<up-button  @tap="getCode" :text="tips" type="primary" plain size="normal" 
												:disabled="disabled1"></up-button>
						</template>
						</up-input>
						
				</up-form-item>

				<up-form-item label="真实姓名" prop="name" labelWidth="70"
					>
					<up-input v-model="loginForm.name" placeholder="请输入真实姓名" border="none"
						placeholder-style="color: #888888"></up-input>
				</up-form-item>

				<!-- 企业名称选择 -->
				<up-form-item label="企业名称" prop="corp" labelWidth="70">
					<up-input 
						v-model="loginForm.corpName" 
						placeholder="请选择企业" 
						readonly 
						border="none"
						placeholder-style="color: #888888"
						suffixIcon="arrow-down"
						@tap="showCorpPicker = true"
					></up-input>
				</up-form-item>
				
				<!-- 职务选择 -->
				<up-form-item label="职务" prop="job" labelWidth="70">
					<up-input 
						v-model="loginForm.jobName" 
						placeholder="请选择职务" 
						readonly 
						border="none"
						placeholder-style="color: #888888"
						suffixIcon="arrow-down"
						@tap="showJobPicker = true"
					></up-input>
				</up-form-item>
			</up-form>

			<!-- 企业名称选择器 -->
			<up-picker 
				:show="showCorpPicker" 
				mode="selector"
				v-model="selectedCorp" 
				:columns="corpOptions" 
				keyName="name" 
				valueName="id"
				title="请选择企业"
				@confirm="onCorpConfirm"
				@cancel="onCorpCancel"
			></up-picker>
			
			<!-- 职务选择器 -->
			<up-picker 
				:show="showJobPicker" 
				mode="selector"
				v-model="selectedJob" 
				:columns="jobOptions" 
				keyName="name" 
				valueName="id"
				title="请选择职务"
				@confirm="onJobConfirm"
				@cancel="onJobCancel"
			></up-picker>

			<!-- 注册按钮 -->
			<view class="form-item" style="margin-top: 30px;">
				<up-button text="注册" type="primary" shape="round" size="large"
					custom-style="background: linear-gradient(180deg, #4A90E2 0%, #2C84E8 100%); border: none; height: 50px; color: #fff; font-weight: 500; border-radius: 8px;"
					@click="handleLogin" :loading="loading">
				</up-button>
			</view>

			<!-- 注册链接 -->
			<view class="form-item"
				style="text-align: center; margin-top: 20px;">
				<view style="white-space: nowrap;">
					<text style="color: #000000; font-size: 14px;">已有账号，</text>
					<text style="color: #1989fa; font-size: 14px; text-decoration: underline;" @click="goLogin">去登录</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, reactive } from 'vue';
import * as Auth from "@/api/auth.js"
import * as Job from "@/api/job.js"
import * as Corp from "@/api/corp.js"
// 表单引用
const form = ref(null);

// 响应式数据
const loading = ref(false);
const sendCodeLoading = ref(false);
const tips = ref('获取验证码');
const disabled1 = ref(false);
let timer = null;

// 表单数据
	const loginForm = reactive({
		phone: '',
		code: '',
		name: '',
		corpId: 0,
		corpName: '',
		jobId: 0,
		jobName: ''
	});
	
	// 选择器显示控制
	const showCorpPicker = ref(false);
	const showJobPicker = ref(false);
	
	// 选中的值
	const selectedCorp = ref([1]); // 使用数组格式，与u-picker的多列选择器保持一致
	const selectedJob = ref([1]); // 使用数组格式，与u-picker的多列选择器保持一致
// 企业职务选项 - 保持嵌套数组结构但不使用reactive
	const jobOptions = reactive([[
		// {
		// 	id: 1,
		// 	name: '企业管理员',
		// 	value: '1'
		// },
		// {
		// 	id: 2,
		// 	name: '普通员工',
		// 	value: '2'
		// }
	]]);
	// 企业选项 - 保持嵌套数组结构但不使用reactive
	const corpOptions = reactive([[
		// {
		// 	id: 1,
		// 	enterpriseName: '企业1',
		// 	value: '1'
		// },
		// {
		// 	id: 2,
		// 	enterpriseName: '企业2',
		// 	value: '2'
		// }
	]]);
	Job.getList().then(res=>{
		if(res.code == 200){
			jobOptions[0].splice(0, jobOptions[0].length)
			res.data.list.forEach(item => {
				jobOptions[0].push({
					id: item.id,
					name: item.name,
					value: item.id
				})
			})
		}else{
			
		}
	})
	Corp.getList().then(res=>{
		if(res.code == 200){
			corpOptions[0].splice(0, corpOptions[0].length)
			res.data.list.forEach(item => {
				corpOptions[0].push({
					id: item.id,
					name: item.enterpriseName,
					value: item.id
				})
			})
		}else{
			
		}
	})

	
	// 企业选择确认
	const onCorpConfirm = () => {
		// 查找选中的企业对象
		try {
			const selectedItem = corpOptions[0].find(item => item.id === selectedCorp.value[0]);
			if (selectedItem) {
				loginForm.corpId = selectedItem.id;
				loginForm.corpName = selectedItem.name;
				// 手动触发表单验证，确保选择后验证状态正确
				if (form.value) {
					form.value.validateField('corpId');
				}
			}
		} catch (error) {
			console.error('查找企业对象时出错:', error);
		}
		showCorpPicker.value = false;
	};
	
	// 企业选择取消
	const onCorpCancel = () => {
		showCorpPicker.value = false;
	};
	
	// 职务选择确认
	const onJobConfirm = () => {
		// 查找选中的职务对象
		try {
			const selectedItem = jobOptions[0].find(item => item.id === selectedJob.value[0]);
			if (selectedItem) {
				loginForm.jobId = selectedItem.id;
				loginForm.jobName = selectedItem.name;
				// 手动触发表单验证，确保选择后验证状态正确
				if (form.value) {
					form.value.validateField('jobId');
				}
			}
		} catch (error) {
			console.error('查找职务对象时出错:', error);
		}
		showJobPicker.value = false;
	};
	
	// 职务选择取消
	const onJobCancel = () => {
		showJobPicker.value = false;
	};

// 表单验证规则
const rules = {
	phone: [
		{
			required: true,
			message: '请输入手机号',
			trigger: ['blur', 'change'],
		},
	],
	name: [
		{
			required: true,
			message: '请输入姓名',
			trigger: ['blur', 'change'],
		},
	],
	corpId: [
		{
			required: true,
			message: '请选择企业',
			trigger: ['blur', 'change'],
			// 自定义验证函数，确保值有效
			validator: (rule, value, callback) => {
				if (value && value > 0) {
					callback();
				} else {
					callback(new Error('请选择企业'));
				}
			}
		},
	],
	jobId: [
		{
			required: true,
			message: '请选择职务',
			trigger: ['blur', 'change'],
			// 自定义验证函数，确保值有效
			validator: (rule, value, callback) => {
				if (value && value > 0) {
					callback();
				} else {
					callback(new Error('请选择职务'));
				}
			}
		},
	],
	code: [
		{
			required: true,
			message: '请输入验证码',
			trigger: ['blur', 'change'],
		},
	],
};

// 获取验证码
const getCode = () => {
	// 复用原有的验证逻辑
	if (!loginForm.phone.trim()) {
		uni.showToast({
			title: '请输入手机号',
			icon: 'none'
		});
		return;
	}
	
	if (!/^1[3-9]\d{9}$/.test(loginForm.phone)) {
		uni.showToast({
			title: '请输入正确的手机号',
			icon: 'none'
		});
		return;
	}

	disabled1.value = true;
	let second = 60;
	tips.value = `${second}秒后重新获取`;

	Auth.getCode(loginForm.phone).then(res=>{
		if(res.code === 200){
			console.log(res.data)
			uni.showToast({
				title: '验证码发送成功',
				icon: 'success'
			});
		}else{
			uni.showToast({
				title: '验证码发送失败',
				icon: 'error'
			});
		}
	})

	// 倒计时
	timer = setInterval(() => {
		second--;
		tips.value = `${second}秒后重新获取`;
		if (second <= 0) {
			clearInterval(timer);
			tips.value = '获取验证码';
			disabled1.value = false;
		}
	}, 1000);
};

// 原始方法保留，防止其他地方调用
const getVerificationCode = () => {
	if (!loginForm.phone.trim()) {
		uni.showToast({
			title: '请输入手机号',
			icon: 'none'
		});
		return;
	}

	if (!/^1[3-9]\d{9}$/.test(loginForm.phone)) {
		uni.showToast({
			title: '请输入正确的手机号',
			icon: 'none'
		});
		return;
	}

	sendCodeLoading.value = true;
	// 模拟发送验证码
	setTimeout(() => {
		sendCodeLoading.value = false;
		uni.showToast({
			title: '验证码发送成功',
			icon: 'success'
		});
	}, 1500);
};

// 注册函数
	const handleLogin = () => {
		// 表单验证
		if (form.value) {
			form.value.validate().then(valid => {
				if (valid) {
					loading.value = true;
					let loginParam = {
						phone: loginForm.phone,
						name: loginForm.name,
						userName: loginForm.phone,
						corpId: loginForm.corpId,
						jobId: loginForm.jobId,
						code: loginForm.code
					};
					Auth.miniRegister(loginParam).then(res=>{
						if(res.code == 200){
							// 注册成功提示 - 等待企业审核通过
							uni.showModal({
								title: '提交成功',
								content: '等待企业审核通过～',
								showCancel: false,
								confirmText: '知道了',
								success: (res) => {
									if (res.confirm) {
										// 点击知道了后跳转到登录页
										uni.redirectTo({
											url: '/pages/login/login'
										});
									}
								}
							});
						}else{
							uni.showToast({
								title: res.msg,
								icon: 'error'
							});
						}
						loading.value = false;
					}).catch(res=>{
						console.error(res)
						loading.value = false;
					})
				} else {
					uni.$u.toast('校验失败，请检查信息是否完整');
				}
			}).catch(() => {
				// 处理验证错误
				uni.$u.toast('校验失败，请检查信息是否完整');
			});
		} else {
			uni.$u.toast('表单初始化失败');
		}
	};

// 忘记密码
const forgotPassword = () => {
	uni.showToast({
		title: '忘记密码功能待开发',
		icon: 'none'
	});
};

// 注册
const goLogin = () => {
	uni.navigateTo({
		url: '/pages/login/login'
	});
};
</script>

<style lang="scss">
	.status-bar-placeholder {
		height: 44px;
	}
.u-page {
	background: linear-gradient(180deg, #4A90E2 0%, #fff 100%);
	min-height: 100vh;
	position: relative;
}

.login-logo {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 60px 0 60px 0;
}

.edit-form {
	>view {
		margin-bottom: 15px;
		padding: 8px 10px;
		border-radius: 10px;
		background-color: #ffffff;
	}
}

.login-form {
	padding: 0 40px;

	.form-item {
		margin-bottom: 15px;
	}
}
</style>